const seq_num_length = 16; // 序列号长度
let seqNum = 0; // 序列号
const cache = {}; // 缓存
const dupCache = {}; // 重复帧缓存
let expectedSeq = "0".repeat(seq_num_length); // 期望序列号

function sendFrame(frame) {
  const seq = seqNum.toString(2).padStart(seq_num_length, '0'); // 生成序列号
  frame.seq = seq; // 添加序列号
  linkLayer.sendFrame(frame); // 发送帧
  cache[seq] = frame;
  const linkTimer = setTimeout(() => {
    resendFrame(seq);
  }, 500);
  timers[seq] = timer;
  seqNum++;
}

function resendFrame(seq) {
  const frame = cache[seq];
  if (frame) {
    sendFrame(frame);
  }
}

function receiverFrame(frame) {
  if (frame.seq === expectedSeq) {
    handleFrame(frame);
    expectedSeq = incSeq(expectedSeq);
  } else {
    if (dupCache[frame.seq]) {
      console.log('Duplicated frame:', frame.seq);
      return;
    } else {
      processFrame(frame);
      sendWindow.add(frame.seq);
      if (sendWindow.full()) {
        sendWindow.slide();
      }
      dupCache[frame.seq] = true;
      sendAck(frame.seq);
    }
  }
}

function sendAck(seq) {
  let ackFrame = {
    type: 'ack',
    seq: seq
  };
  linkLayer.sendFrame(ackFrame);
  sendWindow.remove(sendWindow.first());
  sendWindow.slide();
}
